<?php
define( '__ESPACE__', 'admin');
$prefix = '../../';
require_once($prefix.'starter.php');

ob_start();

$PWE_admin = new controler_admin();

/* parsing get datas */
if(isset($_POST)&&isset($_POST['maxWidth'])&&$_POST['maxWidth']>0){
    $_GET['max_width'] = $_POST['maxWidth'];
}
if(isset($_POST)&&isset($_POST['maxHeight'])&&$_POST['maxHeight']>0){
    $_GET['max_height'] = $_POST['maxHeight'];
}

$maxWidth = (isset($_GET['max_width']) && $_GET['max_width']>0)?$_GET['max_width']:0;
$maxHeight = (isset($_GET['max_height']) && $_GET['max_height']>0)?$_GET['max_height']:0;

$modeleId = (isset($_GET) && isset($_GET['modele_id']) && $_GET['modele_id']>0)?$_GET['modele_id']:0;
$modeleType = (isset($_GET) && isset($_GET['modele']))?$_GET['modele']:'';
$module = (isset($_GET) && isset($_GET['module']))?$_GET['module']:'';
$modele = $PWE_admin->getModele($modeleType, $modeleId, $module);
$media = null;

/* crop image */
$startX = (isset($_POST)&&isset($_POST['x']))?$_POST['x']:0;
$startY = (isset($_POST)&&isset($_POST['y']))?$_POST['y']:0;
$cropWidth = (isset($_POST)&&isset($_POST['longueur']))?$_POST['longueur']:0;
$cropHeight = (isset($_POST)&&isset($_POST['hauteur']))?$_POST['hauteur']:0;

$upload = false;
$errorMsg = '';

if(isset($_GET) && isset($_GET['media_id']) && $_GET['media_id']>0){
    $media = new modele_media($_GET['media_id']);
    
    if(isset($_GET['suppr']) && $_GET['suppr']>0){
        $mode = 'delete';
        if($modele!==null){
            $modele->removeMedia($_GET['media_id']);
        }elseif($modeleType==='' && $media !== null && $media->getId()>0){
            $media->delete();
        }
        $media = null;
    }else{
        $mode = 'update';
    }
}else{
    $mode = 'create';
    $media = new modele_media();
}

$fileName = '';
if(isset($_POST)&&isset($_POST['filename'])&&$_POST['filename']!=''){
    $fileName = $_POST['filename'];
}elseif($media!==null && ($media->getHeight()>0||$media->getMediaTypeId()>1)){
    $fileName = $media->getFileName($prefix);
}

if(isset($_POST) && isset($_POST['submit'])){
    $data = array(
        '_id'=>0,
        '_order'=>0
    );
    $uploader = new controler_upload('uploads/',$prefix);
    
    if(isset($_GET)&&isset($_GET['force_title'])&&$_GET['force_title']!=''){
        $data['_title'] = $_GET['force_title'];
    }else{
        $data['_title'] = (isset($_POST['modele_title']))?$_POST['modele_title']:'';
    }
    $data['_legende'] = (isset($_POST['modele_legende']))?$_POST['modele_legende']:'';
    
    if(isset($_FILES) && isset($_FILES['mediaFile']) && $_FILES['mediaFile']['name'] !== ''){ // un fichier est transmis
        if($uploader->uploadFile($_FILES['mediaFile']['tmp_name'],$_FILES['mediaFile']['name'],array('jpg','gif','png','pdf','doc','docx'))){
            $dossierDest = '';
            if($uploader->getFileType()==='image'){
                $dossierDest = 'images';
                $mediaTypeId = 1;
                $uploader->resizeImage($maxWidth, $maxHeight,$startX,$startY,$cropWidth,$cropHeight);
            }elseif($uploader->getFileType()==='document'){
                $dossierDest = 'documents';
                $mediaTypeId = 2;
            }
            
            if(isset($_GET)&&isset($_GET['sous_dossier'])&&$_GET['sous_dossier']!=''){
                $dossierDest .= '/'.$_GET['sous_dossier'];
            }
            
            $upload = ($dossierDest!=='')?$uploader->saveFile($fileName,$dossierDest):false;
            
            if(!$upload){
                $errorMsg .= $uploader->getErrorMessage();
            }else{
                $data['_path'] = $uploader->getPath();
                $data['_media_type_id'] = $mediaTypeId;
                if($mediaTypeId===1){
                    $data['_width'] = $uploader->getWidth();
                    $data['_height'] = $uploader->getHeight();
                }
            }
        }else{
            $errorMsg .= $uploader->getErrorMessage();
        }
    }elseif($media!==null && ($media->getHeight()>0||$media->getMediaTypeId()>1) && $uploader->loadFile($prefix.$media->getPath(),$media->getFileName($prefix),array('jpg','gif','png','pdf','doc','docx'))){
        $dossierDest = '';
        if($uploader->getFileType()==='image'){
            $dossierDest = 'images';
            $mediaTypeId = 1;
            $uploader->resizeImage($maxWidth, $maxHeight,$startX,$startY,$cropWidth,$cropHeight);
        }else{
            $dossierDest = 'documents';
            $mediaTypeId = 2;
        }
        
        // verification du sous-dossier
        $path = substr($media->getPath(),strrpos($media->getPath(), $dossierDest)+strlen($dossierDest)+1);
        $sousDossiers = substr($path, 0, strrpos($path,'/'));
        if($sousDossiers!==''){
            $sousDossiers = '/'.$sousDossiers;
        }
        
        unlink($prefix.$media->getPath());
        
        $uploader->saveFile($fileName,$dossierDest.$sousDossiers);
        $data['_path'] = $uploader->getPath();
                
        $data['_media_type_id'] = $mediaTypeId;
        if($mediaTypeId===1){
            $data['_width'] = $uploader->getWidth();
            $data['_height'] = $uploader->getHeight();
        }
    }

    if($mode === 'create'){
        if($upload){
            $media->setDatas($data);
            $media->save();
            $data['_id'] = $media->getId();
            $data['_path'] = $media->getUrl($prefix);
            $fileName = $media->getFileName($prefix);
            if($data['_id']>0){
                if($modele!==null){
                    $result = $modele->addMedia($data['_id']);
                    if(isset($result)&&($result['success'] || $result)){
                        $data['_order'] = (isset($result['order']))?$result['order']:0;
                    }else{
                        // erreur save media
                        $errorMsg .= "\n\r".' Erreur de rattachement du média.';
                    }
                }
                $mode = 'update';
                $_GET['media_id'] = $data['_id'];
            }else{
                // erreur save media
                $errorMsg .= "\n\r".' Erreur de sauvegarde du média.';
            }
        }else{
            // erreur upload
            $errorMsg .= "\n\r".' Erreur de transfert du fichier.';
        }
    }elseif($mode === 'update'){
        $media->setDatas($data);
        $media->update();
        $fileName = $media->getFileName($prefix);
        $data['_id'] = $media->getId();
        $data['_path'] = $media->getUrl($prefix);
    }
}
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Ajouter/modifier un média</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="robots" content="noindex,nofollow">
        <link href='http://fonts.googleapis.com/css?family=Grand+Hotel' rel='stylesheet' type='text/css'>
        <link href="../../css/skeleton/base.css" type="text/css" rel="stylesheet" media="all"/>
        <link href="../../css/skeleton/skeleton.css" type="text/css" rel="stylesheet" media="all"/>
        <link href="../css/style.css" type="text/css" rel="stylesheet" media="all"/>
        <link href="../../css/jcrop/jcrop.css" type="text/css" rel="stylesheet" media="all"/>
        <link href="<?php echo $PWE_admin->getUiThemePath(); ?>" type="text/css" rel="stylesheet" media="all"/>
        <script src="<?php echo $PWE_admin->getBaseURL(); ?>js/libs/jquery/jquery.js" type="text/javascript"></script>
        <script src="<?php echo $PWE_admin->getBaseURL(); ?>js/libs/jqueryui/jquery-ui.js" type="text/javascript"></script>
        <script src="<?php echo $PWE_admin->getBaseURL(); ?>js/libs/ckeditor/ckeditor.js" type="text/javascript"></script>
        <script src="<?php echo $PWE_admin->getBaseURL(); ?>js/libs/DataTables-1.9.4/media/js/jquery.dataTables.min.js" type="text/javascript"></script>
        <script src="<?php echo $PWE_admin->getBaseURL(); ?>js/libs/jqueryui/jquery-ui-datepicker-fr.js" type="text/javascript"></script>
        <script src="<?php echo $PWE_admin->getBaseURL(); ?>js/libs/jqueryui/jquery-ui-timepicker-fr.js" type="text/javascript"></script>
        <script src="../../js/libs/jcrop/jquery.Jcrop.min.js" type="text/javascript"></script>
        
        <script>
            var baseUrl = "<?php echo $PWE_admin->getBaseUrl(); ?>";
        </script>
        <script src="../js/script.js?v=0.2" type="text/javascript"></script>
        <style>
            form{margin: 10px 0;}
            .fields-file,.action{padding: 10px;}
            .container-image{
                background-color: #FFFFFF;
            }
            .container-image img{
                width: 100%;
                background-color: #FFFFFF;
            }
            input.coord{
                display: inline;
                width: 50px;
            }
            .edit-image{
                padding: 10px;
                border: #F2F2F2 thin solid;
            }
            textarea.legende{
                height: 50px;
            }
            input.titre{
                width: 95%;
            }
        </style>
    </head>
    <body>
<?php if($mode==='delete'): ?>
        <script type="text/javascript">
            var origine = window.top;
            $(document).ready(function(){
                <?php if($modeleType==='galerie' || $modeleType===''): ?>
                origine.closeDialogBox(true);
                <?php else: ?>
                origine.closeDialogBox();
                <?php endif; ?>
            });
        </script>
        <p>Suppression en cours...</p>
        
<?php elseif($mode==='update'): ?>
        <script type="text/javascript">
            var origine = window.top;
            <?php if(isset($_POST)&&isset($_POST['submit'])&&!$upload): ?>
            origine.updateMedia({modele: '<?php echo $modeleType; ?>',module: '<?php echo $module; ?>',order: <?php echo $data['_order']; ?>, media_id: <?php echo $data['_id']; ?>, modele_id: <?php echo $_GET['modele_id']; ?>, path: "<?php echo $data['_path']; ?>", title: "<?php echo $data['_title']; ?>", legende: "<?php echo $data['_legende']; ?>",maxWidth: <?php echo $maxWidth; ?>,maxHeight: <?php echo $maxHeight; ?>});
            <?php endif; ?>
                
            $(document).ready(function(){
                $('.pwe-ui-btn').button();

                $('#file').change(function(){
                    var filePath = $('#file').val();
                    var fileName = filePath.slice(filePath.lastIndexOf('\\')+1);
                    $('#file-name').val(fileName);
                    fileName = fileName.slice(0,fileName.lastIndexOf('.'));
                    if($('#title').val() === '')$('#title').val(fileName);
                });

                $('form').submit(function(){
                    if( $('#title').val() !== '' && $('#file-name').val() !== '' ){
                        if($('#file').val() !== '' || $('#submit').val() === 'Modifier'){
                            return true;
                        }else{
                            return false;
                        }
                    }else{
                        return false;
                    }
                });

                $('#picture').Jcrop({
                    onSelect: showCoords,
                    onChange: showCoords
                });
            });
            var showCoords = function(c){
                // c.x, c.y, c.x2, c.y2, c.w, c.h
                var originalWidth = parseInt($('#original-width').val());
                //var originalHeight = parseInt($('#original-height').val());
                
                var width = $('#picture').width();
                //var height = $('#picture').height();
                
                var ratio = width/originalWidth;
                
                $('#x').val(Math.round(c.x/ratio));
                $('#y').val(Math.round(c.y/ratio));
                $('#newwidth').val(Math.round(c.w/ratio));
                $('#newheight').val(Math.round(c.h/ratio));
            }
        </script>
        <form method="post" enctype="multipart/form-data" accept-charset="UTF-8" action="?modele=<?php echo $modeleType; ?>&modele_id=<?php echo (isset($_GET['modele_id']))?$_GET['modele_id']:0; ?>&media_id=<?php echo (isset($_GET['media_id']))?$_GET['media_id']:0; ?>&max_width=<?php echo (isset($_GET['max_width']))?$_GET['max_width']:0; ?>&max_height=<?php echo (isset($_GET['max_height']))?$_GET['max_height']:0; ?>&force_title=<?php echo (isset($_GET['force_title']))?$_GET['force_title']:''; ?>&sous_dossier=<?php echo (isset($_GET['sous_dossier']))?$_GET['sous_dossier']:''; ?>">
            <div class="container">
                <div class="ten columns">
                    <?php if($media->getHeight()>0): ?>
                    <div class="container-image"><img id="picture" src="<?php echo $media->getUrl($prefix); ?>" style="max-width: <?php echo $media->getWidth(); ?>px;" /></div>
                    <?php endif; ?>
                </div>
                <div class="columns six">
                        <?php if(isset($_GET['force_title'])&&$_GET['force_title']!==''): ?>
                        <label>Titre : </label><?php echo $_GET['force_title']; ?>
                        <input id="title" type="hidden" name="modele_title" value="<?php echo $media->getTitle(); ?>" />
                        <?php else: ?>
                        <?php echo $PWE_admin->getInputHtml('Titre :', 'modele_title', $media->getTitle(),'media', $media->getId(), array('class_input'=>'titre','balise_titre'=>'label')); ?>
                        <?php endif; ?>
                    <label>Nom du fichier : </label><input id="file-name" class="titre" type="text" name="filename" value="<?php echo $fileName; ?>" />
                    
                        <?php echo $PWE_admin->getTextareaHtml('Légende :', 'modele_legende', $media->getLegende(), 'media', $media->getId(), array('class_input'=>'legende','editor'=>0,'balise_titre'=>'label')); ?>
                    <?php if($media->getHeight()>0): ?>
                        <div class="edit-image">
                            <label>Modifier l'image : </label>
                            x : <input type="text" class="coord" name="x" id="x" value="0" />
                            y : <input type="text" class="coord" name="y" id="y" value="0" />
                            longueur : <input type="text" class="coord" name="longueur" id="newwidth" value="<?php echo $media->getWidth(); ?>" />
                            hauteur : <input type="text" class="coord" name="hauteur" id="newheight" value="<?php echo $media->getHeight(); ?>" />
                            <input type="hidden" name="original-width" id="original-width" value="<?php echo $media->getWidth(); ?>" />
                            <input type="hidden" name="original-height" id="original-height" value="<?php echo $media->getHeight(); ?>" />
                            <label>Redimensionner l'image : </label>
                            largeur maximum : <input type="text" class="coord" name="maxWidth" value="<?php echo $maxWidth; ?>" /> 
                            hauteur maximum : <input type="text" class="coord" name="maxHeight" value="<?php echo $maxHeight; ?>" />
                        </div>
                        <?php endif; ?>
                    <div class="fields-file">
                        <label>Modifier le fichier : </label>
                        <input type="hidden" name="MAX_FILE_SIZE" value="2097152" />
                        <input id="file" type="file" name="mediaFile" value="" /> (max 2 Mo)<br/>
                    </div>
                    <div class="action">
                        <input id="submit"  type="submit" name="submit" value="<?php echo ($mode==='create')?'Ajouter':'Modifier'; ?>" class="pwe-ui-btn"/>
                        <?php if($modeleType!==''): ?><input id="choose"  type="button" name="choose" value="Choisir un média existant" class="pwe-ui-btn" onclick="javascript:origine.openSelectMedia(<?php echo (isset($_GET['modele_id']))?$_GET['modele_id']:0; ?>,'<?php echo $modeleType; ?>');"/><?php endif; ?>
                    </div>
                </div>
            </div>
        </form>
<?php elseif($mode==='create'): ?>
        <script type="text/javascript">
            var origine = window.top;
            $(document).ready(function(){
                $('.pwe-ui-btn').button();

                $('#file').change(function(){
                    var filePath = $('#file').val();
                    var fileName = filePath.slice(filePath.lastIndexOf('\\')+1);
                    $('#file-name').val(fileName);
                    fileName = fileName.slice(0,fileName.lastIndexOf('.'));
                    if($('#title').val() === '')$('#title').val(fileName);
                });

                $('form').submit(function(){
                    if( $('#title').val() !== '' ){
                        if($('#file').val() !== '' || $('#submit').val() === 'Modifier'){
                            $('#form-fields').hide();            
                            $('#loading').show();
                            return true;
                        }else{
                            return false;
                        }
                    }else{
                        return false;
                    }
                });
            });
        </script>
        
        <form method="post" enctype="multipart/form-data" accept-charset="UTF-8" action="?modele=<?php echo $modeleType; ?>&modele_id=<?php echo (isset($_GET['modele_id']))?$_GET['modele_id']:0; ?>&media_id=<?php echo (isset($_GET['media_id']))?$_GET['media_id']:0; ?>&max_width=<?php echo (isset($_GET['max_width']))?$_GET['max_width']:0; ?>&max_height=<?php echo (isset($_GET['max_height']))?$_GET['max_height']:0; ?>&force_title=<?php echo (isset($_GET['force_title']))?$_GET['force_title']:''; ?>&sous_dossier=<?php echo (isset($_GET['sous_dossier']))?$_GET['sous_dossier']:''; ?>">
            <div id="form-fields">
                <div class="fields-file text-center">    
                    <label>Fichier : </label>
                    <input type="hidden" name="MAX_FILE_SIZE" value="2097152" />
                    <input id="file" type="file" name="mediaFile" value="" /> (max 2 Mo)<br/>
                    <input id="title" type="hidden" name="modele_title" value="" />
                    <input id="file-name" type="hidden" name="filename" value="" />
                </div>
                <div class="action text-center">
                    <input id="submit"  type="submit" name="submit" value="Envoyer" class="pwe-ui-btn"/>
                    <?php if($modeleType!==''): ?><input id="choose"  type="button" name="choose" value="Choisir un média existant" class="pwe-ui-btn" onclick="javascript:origine.openSelectMedia(<?php echo (isset($_GET['modele_id']))?$_GET['modele_id']:0; ?>,'<?php echo $modeleType; ?>');"/><?php endif; ?>
                </div>
            </div>
            <div id="loading" style="display: none;">
                <h4 class="text-center">Chargement en cours...</h4>
            </div>
        </form>
<?php endif; ?>
        <p><?php echo $errorMsg; ?></p>
        
        <div id="dialogBox" title="">
            <iframe src="" width="100%" height="96%" style="margin:0; padding: 0; border: 0;" />
        </div>
    </body>
</html>
<?php ob_end_flush(); ?>